//
//  ZZLetterCell.m
//  QQplayground
//
//  Created by zhangxy on 2018/8/15.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "ZZLetterCell.h"
#import "UserInfoController.h"
#import "SVWebViewController.h"

@interface ZZLetterCell()<ZCTTMLEmojiLabelDelegate>{
    CGFloat maxWidth;
}
@end

@implementation ZZLetterCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    [_labTime setFont:ListElevenFont];
    [_labTime setTextColor:UIColorFromRGB(TextSizeEightColor)];
    
    _imgLeftAvatar.layer.cornerRadius = 22.0f;
    _imgLeftAvatar.layer.masksToBounds = YES;
    
    _imgRightAvatar.layer.cornerRadius = 22.0f;
    _imgRightAvatar.layer.masksToBounds = YES;
    
    [self createLinkLabelStyle:_labMessage];
    
    _ivLayerView = [[UIImageView alloc] init];
    
    maxWidth = ScreenWidth - 44 * 2 - 40 * 2;
}

-(void)dataToView:(LetterEntity *) model{
    
    self.tempModel = model;
    
    _imgLeftAvatar.hidden = YES;
    _imgRightAvatar.hidden = YES;
    
    [self setBackgroundColor:UIColor.clearColor];
    
    // 右边气泡背景图片
    UIImage  *bgImage = [UIImage imageNamed:@"zcicon_pop_green_normal"];
    [self addLinkMessage:_labMessage text:model.message];
//    [_labMessage setAttributedText:attrStr];
    [self autoWidthOfLabelHegith:_labMessage with:maxWidth];
    [_labTime setText:model.add_time];
    
    CGRect f = _labMessage.frame;
    if(f.size.height < 24){
        f.size.height  = 24;
    }
    if([model.from_user_info.user_id isEqual:[UserUtil getUser].user_id]){
        // 右边
        [_labMessage setTextAlignment:NSTextAlignmentRight];
        bgImage = [UIImage imageNamed:@"zcicon_pop_green_normal"];
        bgImage=[bgImage resizableImageWithCapInsets:UIEdgeInsetsMake(30, 5, 5, 15)];
        // 右边气泡绿色
        [_imgContentBg setBackgroundColor:UIColorFromRGB(BgTitleColor)];
        
        _imgRightAvatar.hidden = NO;
        [_imgRightAvatar sd_setImageWithURL:[NSURL URLWithString:convertToString(model.from_user_info.user_avatar)] placeholderImage:[UIImage imageNamed:@"default_image"]];
        
        
        f.origin.x = ScreenWidth - f.size.width - 90;
        _labMessage.frame = f;
        [_imgContentBg setFrame:CGRectMake(ScreenWidth - f.size.width - 100, 40, f.size.width + 30, f.size.height + 20)];
        
    }else{
        [_labMessage setTextAlignment:NSTextAlignmentLeft];
        
        bgImage = [UIImage imageNamed:@"zcicon_pop_green_left_normal"];
        bgImage=[bgImage resizableImageWithCapInsets:UIEdgeInsetsMake(30, 15, 5, 5)];
        
        [_imgContentBg setBackgroundColor:UIColorFromRGB(TextWhiteColor)];
        _imgLeftAvatar.hidden = NO;
        [_imgLeftAvatar sd_setImageWithURL:[NSURL URLWithString:convertToString(model.from_user_info.user_avatar)] placeholderImage:[UIImage imageNamed:@"default_image"]];
        f.origin.x = 70 + 20;
        _labMessage.frame = f;
        [_imgContentBg setFrame:CGRectMake(70, 40, f.size.width + 30, f.size.height + 20)];
    }
    
    // 设置尖角
    [_ivLayerView setImage:bgImage];

    // 设置尖角
    [self.ivLayerView setFrame:_imgContentBg.frame];
    CALayer *layer              = self.ivLayerView.layer;
    layer.frame                 = (CGRect){{0,0},self.ivLayerView.layer.frame.size};
    _imgContentBg.layer.mask = layer;
    [_imgContentBg setNeedsDisplay];
    
    self.frame = CGRectMake(0, 0, ScreenWidth, 92 + f.size.height - 24);
}

-(void)drawRect:(CGRect)rect{
//    CGRect f = _labMessage.frame;
//    if(f.size.height < 24){
//        f.size.height  = 24;
//    }
//    if([self.tempModel.from_user_info.user_id isEqual:[UserUtil getUser].user_id]){
//        f.origin.x = ScreenWidth - f.size.height - 74;
//        _labMessage.frame = f;
//        [_imgContentBg setFrame:CGRectMake(ScreenWidth - f.size.height - 84, 40, f.size.width + 30, f.size.height + 20)];
//
//    }else{
//        f.origin.x = 74 + 20;
//        _labMessage.frame = f;
//        [_imgContentBg setFrame:CGRectMake(74, 40, f.size.width + 30, f.size.height + 20)];
//    }
}



- (CGSize )autoWidthOfLabelHegith:(UILabel *)label with:(CGFloat )width{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(width, FLT_MAX);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    newFrame.size.height = expectedLabelSize.height;
    newFrame.size.width = expectedLabelSize.width;
    label.frame = newFrame;
    [label updateConstraintsIfNeeded];
    
    return expectedLabelSize;
}


-(void)createLinkLabelStyle:(ZCTTMLEmojiLabel *) label{
    [label setTextAlignment:NSTextAlignmentLeft];
    label.numberOfLines = 0;
    [label setFont:FontFiftent];
    [label setTextColor:UIColorFromRGB(TextSizeOneColor)];
    [label setBackgroundColor:UIColor.clearColor];
    [label setLinkColor:UIColorFromRGB(TextLinkColor)];
    [label setDelegate:self];
    label.userInteractionEnabled = YES;
}

-(void)addLinkMessage:(ZCTTMLEmojiLabel *) label text:(NSString *)text{
    text = [ZZCoreTools replaceMessageEmoji:text];
    NSString *sugguestText = [ZZCoreTools transformStringAt:text];
    NSMutableDictionary *sugguestDict = [label getTextADict:sugguestText];
    if(sugguestDict){
        label.text = sugguestDict[@"text"];
        NSArray *sugguestArr = sugguestDict[@"arr"];
        //    [_emojiLabel setText:tempText];
        for (NSDictionary *item in sugguestArr) {
            NSString *text = item[@"htmlText"];
            int loc = [item[@"realFromIndex"] intValue];
            // 一定要在设置text文本之后设置
            [label addLinkToURL:[NSURL URLWithString:item[@"url"]] withRange:NSMakeRange(loc, text.length)];
        }
    }else{
        label.text = text;
    }
}

// 链接点击
-(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url{
    DLog(@"链接地址:%@",url.absoluteString);
    [self doLinkClick:url.absoluteString];
    
}

// 链接点击
-(void)ZCMLEmojiLabel:(ZCTTMLEmojiLabel *)emojiLabel didSelectLink:(NSString *)link withType:(ZCTTMLEmojiLabelLinkType)type{
    DLog(@"意外添加的：%@",link);
    [self doLinkClick:link];
}


-(void)doLinkClick:(NSString *) url{
    if([url hasPrefix:@"name://"]){
        return;
    }
    if([url hasPrefix:@"uid://"]){
        UserInfoController *vc = [[UserInfoController alloc] init];
        vc.user_id = [url stringByReplacingOccurrencesOfString:@"uid://" withString:@""];
        if(self.delegate && [self.delegate respondsToSelector:@selector(onCellItemClick:obj:)]){
            [self.delegate onCellItemClick:ZZClickOpenVC obj:vc];
        }
    }else{
        if([url hasPrefix:@"tel:"] || validateNumber(url)){
            NSString *callURL = [url stringByReplacingOccurrencesOfString:@"tel:" withString:@""];
            [[AlertUtil shareInstance] showAlert:nil message:callURL cancelTitle:@"取消" titleArray:@[@"呼叫"] viewController:(UIViewController *)self.delegate confirm:^(NSInteger buttonTag) {
                if(buttonTag == 0){
                    // 打电话
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callURL]];
                }
            }];
        }else if([url hasPrefix:@"mailto:"] || validateEmail(url)){
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        }else{
            if (![url hasPrefix:@"https"] && ![url hasPrefix:@"http"]) {
                url = [@"https://" stringByAppendingString:url];
            }
            
            SVWebViewController *vc = [[SVWebViewController alloc] initWithURL:[NSURL URLWithString:url]];
            if(self.delegate && [self.delegate respondsToSelector:@selector(onCellItemClick:obj:)]){
                [self.delegate onCellItemClick:ZZClickOpenVC obj:vc];
            }
        }
    }
    
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
